/*
 * @Author: fisher
 * @Date: 2024-02-22 15:23:15
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-03-27 14:51:39
 * @FilePath: \allfront\src\hooks\useBigfileUpload.js
 * @Description:
 */
import { ref, reactive } from 'vue';
import { useAxios } from '@/hooks/useAxios';
export default function useFileUpload() {
  const { post, get } = useAxios();
  const uploading = ref(false); // 上传状态
  const progress = ref(0); // 上传进度
  const mergeProgress = reactive({
    status: true,
  });
  const combineRes = reactive({});
  const uploadFileChunks = async (file, type) => {
    const chunkSize = 10 * 1024 * 1024; // 每个分片的大小
    const chunks = Math.ceil(file.size / chunkSize); // 总分片数
    let currentChunk = 0;
    const uploadChunk = async chunk => {
      const formData = new FormData();
      formData.append('file', chunk);
      formData.append('name', file.name);
      formData.append('chunk', currentChunk + 1); // 分片序号，从1开始
      formData.append('chunks', chunks); // 总分片数

      try {
        const response = await post('/upload/bigFile', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });

        if (response.status) {
          // 分片上传成功，更新进度
          currentChunk++;
          progress.value = (currentChunk / chunks) * 100;

          // 上传下一分片
          if (currentChunk < chunks) {
            const nextChunkStart = currentChunk * chunkSize;
            const nextChunkEnd = Math.min(
              nextChunkStart + chunkSize,
              file.size,
            );
            const nextChunk = file.slice(nextChunkStart, nextChunkEnd);
            uploadChunk(nextChunk);
          } else {
            // 所有分片上传完毕
            uploading.value = false;
            // ElNotification({
            //   title: 'Info',
            //   message: '正在合并分片...',
            //   type: 'info',
            // });
            // 发起合并
            post('/upload/merge', {
              name: file.name,
              chunks,
              type,
            }).then(res => {
              // console.log('merge res', res);
              const taskId = res.data;

              const timer = setInterval(async () => {
                const progressResponse = await get(
                  `/upload/getMergeProgress/${taskId}`,
                );
                // console.log('progressResponse', progressResponse);
                // Object.assign(mergeProgress, progressResponse.data);
                mergeProgress.status = progressResponse.data.status;
                mergeProgress.data = progressResponse.data.data;
                if (progressResponse.data.status) {
                  ElMessage({
                    message: '合并完成！',
                    type: 'success',
                  });
                  clearInterval(timer);
                  // console.log('progressData', progressData);
                  const data = {
                    originalFilename:
                      progressResponse.data.data.originalFilename,
                    path: progressResponse.data.data.path,
                  };
                  combineRes.data = data;
                  // 合并完成进度归0
                  progress.value = 0;
                }
              }, 2000);
            });
          }
        } else {
          console.error('分片上传失败', response.data);
          uploading.value = false;
        }
      } catch (error) {
        console.error('上传过程中出错', error);
        uploading.value = false;
      }
    };
    // 查询是否存在同名大文件
    get('/upload/checkExistence', {
      name: file.name,
    })
      .then(res => {
        // 检测到同名大文件res = undefind，未检测到res为一个对象
        if (!res) return;
        // 开始上传第一块分片
        uploading.value = true; // 开始上传
        const firstChunk = file.slice(0, chunkSize);
        uploadChunk(firstChunk);
      })
      .catch(err => {
        console.log(err);
      });
  };

  return {
    uploading,
    progress,
    mergeProgress,
    uploadFileChunks,
    combineRes,
  };
}
